package com.cjm.one.security.service;

import com.cjm.one.common.constant.SecurityConstants;
import com.cjm.one.common.result.Result;
import com.cjm.one.custom.client.CustomerInfoClient;
import com.cjm.one.model.custom.entity.CustomerInfo;
import com.cjm.one.model.system.entity.SysUserInfo;
import com.cjm.one.security.custom.AppCustomer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Slf4j
@Service("appUserDetailsService")
public class AppUserDetailsService implements UserDetailsService {
    private static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$");

    @Resource
    private CustomerInfoClient customerInfoClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 判断登录标识类型
        LoginIdentifier identifier = resolveLoginIdentifier(username);

        Result<CustomerInfo> result = switch (identifier) {
            case EMAIL -> customerInfoClient.byEmail(username, SecurityConstants.INNER);
            case MOBILE -> customerInfoClient.byPhone(username, SecurityConstants.INNER);
            case INVALID -> throw new UsernameNotFoundException("登录标识格式错误");
        };

        return processUserInfo(result);
    }


    private LoginIdentifier resolveLoginIdentifier(String username) {
        boolean isEmail = EMAIL_PATTERN.matcher(username).matches();
        boolean isMobile = MOBILE_PATTERN.matcher(username).matches();

        if (isEmail && isMobile) {
            throw new UsernameNotFoundException("登录标识同时符合邮箱和手机号格式");
        }
        if (isEmail) return LoginIdentifier.EMAIL;
        if (isMobile) return LoginIdentifier.MOBILE;
        return LoginIdentifier.INVALID;
    }

    private UserDetails processUserInfo(Result<CustomerInfo> result) {
        if (result == null || !result.isSuccess()) {
            log.error("用户服务调用失败: {}", result);
            throw new UsernameNotFoundException("用户服务不可用");
        }

        CustomerInfo customerInfo = result.getData();
        if (customerInfo == null) {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }

        if (customerInfo.getStatus().equals('2')) {
            log.warn("账号已禁用: {}", customerInfo.getStatus());
            throw new UserStatusException("账号已禁用");
        }
        log.info("用户登录: {}", customerInfo.getNickname());
        return new AppCustomer(customerInfo);
    }

    // 登录标识类型枚举
    private enum LoginIdentifier {
        EMAIL, MOBILE, INVALID
    }

    // 自定义状态异常
    public static class UserStatusException extends AuthenticationException {
        public UserStatusException(String msg) {
            super(msg);
        }
    }
}
